package bjh.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wenchang
 * @create 2020-10-30-23:04
 */
@Slf4j
@Service
public class ClarwerService {
    public JSONObject hourlyNew(String city) throws Exception{
        JSONArray array = new JSONArray();
        Document document = Jsoup.connect("http://m.weathercn.com/hourly-weather-forecast.do?partner=&language=zh-cn&id="+city+"&p_source=&p_type=jump").get();
        Elements selects = document.select("#scroller > ul > li > p");
        ArrayList<String> temprature = new ArrayList<>();
        for (int i=1;i<selects.size();i=i+2){
            String replace = selects.get(i).text().replace("°C", "");
            temprature.add(replace);
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        Elements select = document.select("ol.times_main > li");
        for (int s = 0;s<select.size();s++){
            List<String> collect = select.get(s).select("section > div").stream().map(selects211 -> {
                return selects211.select("p").text().replaceAll("[° C %km/h]","");
            }).collect(Collectors.toList());
            collect.add(select.get(s).select("section > div > span:matches([东南西北])").text());
            String format = simpleDateFormat.format(date);
            Date parse = simpleDateFormat.parse(format);
            parse.setTime(parse.getTime() + 1000 * 60 * 60 *(s+1));
            HashMap<String, Object> map = new HashMap<>();
            map.put("createTime",simpleDateFormat.format(parse));
            map.put("temperature",temprature.get(s));
            map.put("feelsLike",collect.get(0));
            map.put("waterProbability",collect.get(1));
            map.put("windScale",collect.get(2).replace("级",""));
            map.put("humidity",collect.get(3));
            map.put("windSpeed",collect.get(4));
            map.put("dewPoint",collect.get(5));
            map.put("visibility",collect.get(6));
            map.put("clouds",collect.get(7));
            map.put("windDirection",collect.get(8));
            array.add(map);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hourly",array);
        JSONArray array1 = new JSONArray();
        array1.add(jsonObject);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("results",array1);
        return jsonObject1;
    }
}
